package quartz.config;

import org.quartz.Scheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import quartz.listener.MyJobListener;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * javaConfig配置类（用于声明Quartz相关的类）
 */
@Configuration
public class QuartzConfig {


    /**
     * 将Quartz的调度器（Scheduler）交给SpringIOC容器管理
     */
    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws Exception {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.getListenerManager().addJobListener(new MyJobListener());//在调度器上绑定jobListener任务监听器
        return scheduler;
    }

    /**
     * 将Quartz调用器工厂（SchedulerFactoryBean）交给SpringIOC容器管理x
     * @param dataSource 数据源（初始化这个调用器工厂需要一个数据源，因此需要注入一个）
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setDataSource(dataSource);
        factory.setQuartzProperties(quartzProperties());
        factory.setWaitForJobsToCompleteOnShutdown(true);
        return factory;
    }

    public Properties quartzProperties() {
        // 初始化SchedulerFactoryBean时需要设置的一些参数
        Properties properties = new Properties();
        properties.setProperty("org.quartz.jobStore.class", "org.springframework.scheduling.quartz.LocalDataSourceJobStore");
        properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        properties.setProperty("org.quartz.jobStore.tablePrefix", "qrtz_");
        //开启Quartz的集群模式（就是这套程序，无论部署在多少台服务器上，只要数据库是共用一套的，那么这些集群上就不会重复执行任何一个后台任务）
        properties.setProperty("org.quartz.jobStore.isClustered", "true");
        properties.setProperty("org.quartz.jobStoreacquireTriggersWithinLock", "true");
        return properties;
    }
}
